﻿#!/usr/bin/env python

import tornado.web
import os
import hashlib
from control.log import mylog
from control.pool import *
from control.room import RoomMgt

template_fix = '..'+os.sep+'templates'+os.sep

cache = Pool()
roommgt = RoomMgt()


def getIDbyName(s):
    m = hashlib.md5()
    m.update(s)
    return m.hexdigest()


class Login(tornado.web.RequestHandler):
    
    def get(self):
        return self.render(template_fix+'login.html')

    def post(self):
        '''
            -1:no room
            -2:invalid user
        '''
        i = web.input()
        print '>>>>>>>>>>>>>>>>>>'
        print i
        data   = i.keys()[0]
        name   = data.split(',')[0]
        gender = data.split(',')[1]
        roomid = data.split(',')[2]
        mylog.info('Request Login:name(%s),gender(%s),roomid(%s)'%(name,gender,roomid))

        #和web.py不一样，要自己写这个头
        self.set_header("Content-Type", "text/plain")
        
        #取房间
        proom = roommgt.GetRoombyRoomId(roomid)
        if not proom:
            mylog.error('Get Room:roomid(%s) error!'%(roomid))
            self.write('-1:没有找到房间,请重新选择房间.')
        #检查房间里是否有该用户
        id = getIDbyName(name)
        ret = proom.cache.GetObj(id)
        if ret:
            mylog.error('Username(%s) is already exsists!'%(name))
            self.write('-2:对不起,用户已存在,请重新输入用户名')
        else:
            mylog.info('Username(%s) is not find, can enter room!'%(name))
            #这里接受通过验证的用户名并创建用户，页面跳转在ajax的响应里做
            ret = proom.Login(name,gender)
            if ret:
                ret = -1
            else:
                ret = 0
            mylog.info('Login room():ret=(%d)'%(ret))
            self.write('1:nothing')


class Chat(tornado.web.RequestHandler):

    def get(self):
        return self.render(template_fix+'chat.html')
    
#ajax 获取服务器上的房间信息
class GetRoomInfo(tornado.web.RequestHandler):
    
    def get(self):
        data = ''
        for item in roommgt.config:
            data += item.roomname+",%d;"%int(item.roomid)
        self.write(data)
